﻿using Cloud.Core.AuthUser;
using Cloud.Core.Bizlogic;
using Cloud.Core.Model;
using Cloud.Core.ModelSearch;
using Cloud.Core.Response;
using Microsoft.AspNetCore.Mvc;
using Senparc.Weixin.WxOpen.AdvancedAPIs.Sns;
using System.Net.Http;
using System.Threading.Tasks;
using System;
using Cloud.Core.Model.Promotion;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using Microsoft.EntityFrameworkCore.Internal;

namespace Cloud.Core.Controllers
{
   
    /// <summary>
    /// 用户管理
    /// </summary> 
    [Route("api/v1/[controller]")]
    [ApiController]
    public class promotionUsersController : ControllerBase
    {
        private readonly CloudDataBase _context;
        private readonly ModOperate.Mod _thisModel = ModOperate.Mod.MBasicInfo;
        private readonly HttpClient _httpClient;
        public promotionUsersController(CloudDataBase context, HttpClient httpClient)
        {
            _context = context;
            _httpClient = httpClient;
        }

     

        #region 获取用户信息
        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Route("GetById")]
        [HttpGet]
        public async Task<JsonResponse<PromotionUsers>> GetById([FromHeader] string Authorization, string id)
        {

            var _character = Online.GetLoginInfo(Authorization);
            var response = Online.AuthUser<PromotionUsers>(_thisModel, ModOperate.Operate.Search, _character);
            //if (response.Status != ResponseStatus.Success)
            //{
            //    return response;
            //}
            response.Data = await _context.PromotionUsers.FirstOrDefaultAsync(t => t.Id == Convert.ToDouble(id)).ConfigureAwait(false);

            if (response.Data == null)
            {
                response.Status = ResponseStatus.NullData;
                response.Msg = "无数据";
            }
            else
            {
                response.Status = ResponseStatus.Success;
                response.Msg = "查询成功";
            }
            return response;
        }
      
      
        #endregion

        #region 获取分页信息
        /// <summary>
        /// 获取全部用户信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Route("GetList")]
        [HttpPost]
        public async Task<JsonResponse<DataList<object>>> GetList([FromHeader] string Authorization, sPage sUser)
        {
            var _character = Online.GetLoginInfo(Authorization);
            var response = Online.AuthUser<DataList<object>>(_thisModel, ModOperate.Operate.Search, _character);
            //if (response.Status != ResponseStatus.Success)
            //{
            //    return response;
            //}+

            response.Data = new DataList<object>();
            new Helper().sPageNew(sUser);
            var listQuery = _context.PromotionUsers.Where(t => t.Id >= 0 && t.Id <= int.MaxValue);
            if (!string.IsNullOrEmpty(sUser.Field1))
            {
                listQuery = listQuery.Where(t => t.PromotionName.Contains(sUser.Field1));
            }
            if (!string.IsNullOrEmpty(sUser.Field2))
            {
                listQuery = listQuery.Where(t => t.PromotionAddress.Contains(sUser.Field2));
            }
            response.Data.Total = await listQuery.CountAsync().ConfigureAwait(false);
         
            var list = listQuery.Skip((int)sUser.PageIndex * (int)sUser.PageSize)
                   .Take((int)sUser.PageSize).ToArray();
        

            response.Data.Count = list.Length;

            response.Data.List = list;
            response.Msg = "查询成功";
            response.Status = ResponseStatus.Success;
            return response;
        }
        #endregion

     

        #region 用户编辑
        /// <summary>
        /// 用户编辑 
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("PromotionUsersUpdate")]
        public async Task<JsonResponse> PromotionUsersUpdate([FromHeader] string Authorization, PromotionUsers entity = null)
        {
            var _character = Online.GetLoginInfo(Authorization);
            var response = Online.AuthUser(_thisModel, ModOperate.Operate.Add, _character);
            //if (response.Status != ResponseStatus.Success)
            //{
            //    return response;
            //}
            if (entity == null)
            {
                response.Msg = "参数为空";
                response.Status = ResponseStatus.ParameterError;
                return response;
            }
            // var data = await _context.User.FirstOrDefaultAsync(t => t.Id == Convert.ToDouble(entity.Id)).ConfigureAwait(false);
            var promotionUsers = await _context.PromotionUsers.FirstOrDefaultAsync(t => t.Id == Convert.ToDouble(entity.Id));
            if (promotionUsers == null)
            {
                response.Msg = "修改失败,数据不存在";
                response.Status = ResponseStatus.NullData;
                return response;
            }

            promotionUsers.Status = entity.Status;


            _context.Set<PromotionUsers>().Update(promotionUsers);
            int num = _context.SaveChanges();
            if (num > 0)
            {
                response.Msg = "审核成功";
                response.Status = ResponseStatus.Success;
            }
            else
            {
                response.Msg = "审核失败";
                response.Status = ResponseStatus.ProcessFail;
            }
            string et = response.Msg + "-修改数据:" + new Helper().objToJson(entity);
            await new LoggerWriteen().writeAsync(new Log(Log.OperateType.操作, et), RouteData.Values.Values.Join(","));
            return response;
        }

        #endregion

        #region 用户删除
        /// <summary>
        /// 用户删除 
        /// </summary>
        /// <param name="aaa"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("UserDel")]
        public async Task<JsonResponse> UserDel([FromHeader] string Authorization, string ids = null)
        {
            var _character = Online.GetLoginInfo(Authorization);
            var response = Online.AuthUser(_thisModel, ModOperate.Operate.Add, _character);
            //if (response.Status != ResponseStatus.Success)
            //{
            //    return response;
            //}
            if (ids.Length == 0)
            {
                response.Msg = "参数为空";
                response.Status = ResponseStatus.ParameterError;
            }

            string[] arr = ids.TrimEnd(',').Split(',');
            ulong[] barr = new ulong[arr.Length];
            for (int i = 0; i < arr.Length; i++)
            {
                barr[i] = Convert.ToUInt64(arr[i]);
            }
            var users = _context.User.Where(c => barr.Contains(c.Id));

            var dataCount = users.Count();
            if (dataCount == 0)
            {
                response.Msg = "数据不存在,不允许删除";
                response.Status = ResponseStatus.NullData;
                return response;
            }

            string delArr = new Helper().objToJson(users);
            _context.User.RemoveRange(users);

            int num = _context.SaveChanges();
            if (num > 0)
            {
                response.Msg = "用户删除成功";
                response.Status = ResponseStatus.Success;
            }
            else
            {
                response.Msg = "用户删除失败";
                response.Status = ResponseStatus.ParameterError;
            }
            delArr = response.Msg + "-删除集合:" + delArr;
            await new LoggerWriteen().writeAsync(new Log(Log.OperateType.操作, delArr), RouteData.Values.Values.Join(","));
            return response;
        }
        #endregion

     

      
    }
}
